#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Purpose:
# Created: 07/06/2009
# $Id $
# Copyright (c) 2008,2009 by University College London
# Authors:
#  --<>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.
import logging
import subprocess

from enthought.traits.api import HasTraits, Unicode, File, Button, \
     ListUnicode, Int, Dict, Enum, List, Str, ListStr, Bool, Directory, \
     Any
from enthought.traits.ui.api import View, Item, CheckListEditor, EnumEditor, \
     Group, HGroup
from enthought.traits.ui.menu import OKButton, CancelButton
from enthought.pyface.timer import do_later

import irasexport

class IrasInterface(HasTraits):
    """
    This is a Iras Interface dialog allowing to choose a network from a list
    of networks, export the network to a file and run OpenIRAS on it.
    """
    simsys_exe = File(label="IRAS-2010 executable")
    network = Unicode(label="Network")
    networks = List
    
    session = Any
    sub_timesteps = Int(20, label="Total sub-time steps")
    # Fix-me, time step should be equal to project time step (1 week = 7, month = 30, year =365) - Evgeniii 01.04.11
    days_per_period = Int(1, label="Days per time-step")
    total_runs = Int(1, label="Total Runs (for flow factors)")
    default_evaporation_rate = Int(0)
    #yearly_policy = Bool(label="Use a single yearly policy ?")  #Evgeniii 01.04.11 took out yearly policy for now, since its not used
    working_directory = Directory
    user_node_seq = Int(0, label="Use user-defined node sequence?")
    run = Button   
    export = Button
    

    def __init__(self, **traits):
        """
        Overloading the default traits constructor
        """
        super(IrasInterface, self).__init__(**traits)
        if len(self.networks) > 0:
            self.network = self.networks[0]
        def expand_time_step(num):
            '''
            returns number of days in time_step, see module/units.py
            '''
            if num==2:
                return 7
            elif num==3:
                return 14
            elif num==4:
                return 30
            elif num==6:
                return 91
            elif num==7:
                return 365
            else:
                return 1

        days= expand_time_step(self.session.hpproject.time_step)
        self.days_per_period = days



    def _run_fired(self):
        """
        Launch IRAS
        """
        #Evgenii hardwired IRAS exe name to be IRAS-2010.ese 14.04.11
        path= str(self.working_directory) + '\IRAS-2010.exe'
        logging.info("File is %s" % path)
        #Evgenii made Popen open IRAS-2010.exe in the working directory 14.04.11
        pid = subprocess.Popen([path], cwd=self.working_directory).pid
        
    
    def _export_fired(self):
        """
        Export the selected network files
        """
        logging.debug("Export fired")
        do_later.do_later(self.export_to_file)
        
    def export_to_file(self):
        for network in self.session.hpproject.networks:
            if network.name == self.network:
                logging.info("Exporting %s" % self.network)
                exporter = irasexport.IrasExporter()
                exporter.export(network, self.working_directory,
                        self.session.dbsession,
                        self.days_per_period,
                        self.sub_timesteps,
                        self.total_runs,
                        self.default_evaporation_rate,
                        self.user_node_seq)
                # FIXME : add an info about that
                return
        else:
            print "No network named like that ..."
        
    
    traits_view = View(
        Group(
            Item("network", editor=EnumEditor(name="networks")),
            Item("sub_timesteps"),
            Item("days_per_period"),
            Item("total_runs"),
            Item("default_evaporation_rate"),
            #Item("yearly_policy"), #Evgeniii 01.04.11 took out yearly policy for now, since its not used
            Item("user_node_seq"),
            Item("working_directory"),            
            HGroup(
                Item("run", show_label=False),
                Item("export", show_label=False),
            ),
            #label="Parameters"
            ),
        #Evgenii 14.04.11 took out selection of IRAS-2010.exe (it wasn't working), now hard wired making exporter easier to use
        #Group(
        #    Item("simsys_exe"),
        #    label="Configuration"),
        resizable=True,
        buttons=[OKButton, CancelButton],
        title = "IRAS 2010 Exporter"
    )
    
if __name__ == '__main__':
     
    t = IrasInterface(networks=['net1', 'net2', 'net3'])
    t.configure_traits()

